package br.com.sgo.util.hibernate;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

import br.com.caelum.vraptor.ioc.ApplicationScoped;
import br.com.caelum.vraptor.ioc.Component;
import br.com.caelum.vraptor.ioc.ComponentFactory;

@Component
@ApplicationScoped
public class ServiceRegistryCreator implements ComponentFactory<ServiceRegistry> {

	private final Configuration cfg;
	private ServiceRegistry serviceRegistry;

	public ServiceRegistryCreator(Configuration cfg) {
		this.cfg = cfg;
	}

	@PostConstruct
	public void create() {
		ServiceRegistryBuilder builder = new ServiceRegistryBuilder();
		this.serviceRegistry = builder.applySettings(this.cfg.getProperties()).buildServiceRegistry();
	}

	@PreDestroy
	public void destroy() {
		ServiceRegistryBuilder.destroy(this.serviceRegistry);
	}


	public ServiceRegistry getInstance() {
		return this.serviceRegistry;
	}
}